import { defineStore } from "pinia";
import { toRaw, unref } from "vue";
import { RouteRecordRaw } from "vue-router";
import { store } from "@/store";
import { useProjectSetting } from "@/hooks/setting/useProjectSetting";
import { generatorDynamicRouter } from "@/router/generator-routers";

export interface IAsyncRouteState {
  menus: RouteRecordRaw[];
  routers: any[];
  addRouters: any[];
  keepAliveComponents: string[]; // 缓存组件
  isDynamicAddedRoute: boolean; // 是否添加了动态路由
}

export const useAsyncRouteStore = defineStore({
  id: "app-async-route",
  state: (): IAsyncRouteState => ({
    menus: [],
    routers: [],
    addRouters: [],
    keepAliveComponents: [], // 缓存组件
    isDynamicAddedRoute: false, // 是否添加了动态路由
  }),
  getters: {
    getMenus(): RouteRecordRaw[] {
      return this.menus;
    },
    // 是否添加了动态路由
    getIsDynamicAddedRoute(): boolean {
      return this.isDynamicAddedRoute;
    },
  },
  actions: {
    getRouters() {
      return toRaw(this.addRouters);
    },
    // 是否已经添加了动态路由
    setDynamicAddedRoute(added: boolean) {
      this.isDynamicAddedRoute = added;
    },
    // 设置动态路由
    setRouters(routers) {
      this.addRouters = routers;
    },
    // 设置菜单
    setMenus(menus) {
      this.menus = menus;
    },
    // 设置需要缓存的组件
    setKeepAliveComponents(compNames) {
      this.keepAliveComponents = compNames;
    },
    async generateRoutes(data) {
      let accesseRouters;

      // 路由控制方式
      const { getPermissionMode } = useProjectSetting();
      const permissionMode = unref(getPermissionMode);
      if (permissionMode === "BACK") {
        // 后端控制路由
        // 动态获取菜单
        try {
          accesseRouters = await generatorDynamicRouter();
        } catch (error) {
          console.log(error);
        }
      } else {
        // 前端控制路由
      }
      this.setRouters(accesseRouters);
      this.setMenus(accesseRouters);
      return toRaw(accesseRouters);
    },
  },
});

export function useAsyncRouteStoreWithOut() {
  return useAsyncRouteStore(store);
}
